package Top200;

import java.util.LinkedList;
import java.util.List;

/**
 * @author zhangmin
 * @create 2022-02-19 9:48
 * 回溯
 */
public class generateParenthesis22 {
    List<String> res=new LinkedList<>();
    void backtrack(int left,int right,StringBuffer path){
        if (right<left) return;
        if (left<0||right<0) return;
        if (left==0&&right==0){
            res.add(new String(path));
            return;
        }
        int index=path.length();
        //做出选择
        path.append('(');
        backtrack(left-1,right,path);
        path.deleteCharAt(index);
        path.append(')');
        backtrack(left,right-1,path);
        path.deleteCharAt(index);
    }
    public List<String> generateParenthesis(int n) {
        backtrack(n,n,new StringBuffer());
        return res;
    }
}
